package com.netty.io.chatroom;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author zhangbq
 * @since 2020-12-04 18:13
 **/
public class GroupChatServer {
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    private static final Integer PORT = 6667;

    /**
     * @author zhangbq
     **/
    public GroupChatServer() {
        try {
            this.serverSocketChannel = ServerSocketChannel.open();
            this.selector = Selector.open();
            //异步
            serverSocketChannel.configureBlocking(false);
            //绑定端口监听
            serverSocketChannel.bind(new InetSocketAddress(PORT));
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听通道事件
     *
     * @author zhangbq
     **/
    public void listener() {
        //循环处理
        try {
            while (true) {
                //判断是否有事件到来
                int count = selector.select();
                if (count > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()) {
                            //打开通道
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            //配置为异步通道
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            //这时候客户端上线了，提示信息
                            System.out.println("客户端已经上线 ----->>>>> ： "  + socketChannel.getRemoteAddress());
                        }
                        if (key.isReadable()) {
                            readData(key);
                        }
                        //很重要，一定要移除原来的监听事件
                        iterator.remove();
                    }
                } else {
                    System.out.println("没有客户端请求等待状态 ----->>>>>> ");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    private void readData(SelectionKey key) {
        //定义一个SocketChannel，后面可以关闭
        SocketChannel socketChannel;
        try {
            socketChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //读取的数据的长度总数
            int count = socketChannel.read(buffer);
            //接收到数据，进行解析，然后输出
            if (count > 0) {
                //取出数据
                String requestMsg = new String(buffer.array());
                System.out.println("接收到来自客户端的请求数据 ： " + requestMsg);

                //向其他客户端做转发
                notifyOthers(requestMsg, socketChannel);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void notifyOthers(String msg, SocketChannel channel) {
        System.out.println("<<<<<<< Nio 服务器做客户端消息转发 >>>>>>>");
        //遍历所有注册到selector上的channel
        for (SelectionKey key : selector.keys()) {
            //排除自己然后做消息转发
            Channel selectedChannel = key.channel();
            if (selectedChannel instanceof SocketChannel && !selectedChannel.equals(channel)) {
                //做出Buffer，消息进入Buffer然后扔进通道
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                try {
                    ((SocketChannel) selectedChannel).write(wrap);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.err.println("服务端做消息转发时候发生异常，异常信息 ： " + e.getMessage());
                }
            }
        }
    }


    public static void main(String[] args) {
        new GroupChatServer().listener();
    }
}